//this file define parallel classes for use. it include
//thread, mutex, event, timer and so on
//mlcai 2011-06-12

#ifndef THREAD_H
#define THREAD_H

#include "NameSpaceDef.h"

#if !defined(WIN32)
#include <pthread.h>
#define MUTEX_OBJ pthread_mutex_t
#define EVENT_OBJ pthread_cond_t
#define THREAD_ID pthread_t
#else
#include <windows.h>
#define MUTEX_OBJ CRITICAL_SECTION
#define EVENT_OBJ HANDLE
#define THREAD_ID DWORD
#endif

BEGIN_CXX_NAMESPACE_DEFINITION

//---------------------------define Mutex class-------------------------------

class DYNAMIC_API Mutex
{
public:
	Mutex();
	~Mutex();

	void lock();
	void unlock();

private:
	MUTEX_OBJ m_mutex;
};

//-----------------------define Event class--------------------------

class DYNAMIC_API Event
{
public:
	Event();
	~Event();

	enum WAITRE
	{
		OK,
		TIMEOUT
	};

	void set();
	void wait();
	WAITRE wait(long msecs);

private:
	EVENT_OBJ m_event;
#if !defined(WIN32)
	MUTEX_OBJ m_mutex;
#endif
};

//------------------------define Thread class--------------------------

class DYNAMIC_API Thread
{
public:
	virtual ~Thread();

	void start();

	void join();

	static void sleep(long secs);
	static void msleep(long msecs);
	static void usleep(long usecs);

protected:
	Thread();

	virtual void run() = 0;

	THREAD_ID m_tid;
private:
#if !defined(WIN32)
	static void* thread_fun(void* arg);
#else
	static DWORD WINAPI thread_fun(LPVOID lpParam);
	HANDLE m_threadH;
#endif
	bool m_isThreadBegin;
};

END_CXX_NAMESPACE_DEFINITION

#endif
